package com.demo.interceptor;

import com.demo.dto.Result;
import com.demo.utils.UserHolder;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.HttpMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if (HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
            System.out.println("OPTIONS请求，放行");
            return true;
        }
        // 1.判断是否需要拦截（ThreadLocal中是否有用户）
        // 如果有说明在此之前该用户使用token来访问服务器，即用户已登录
        // 否则用户没有登录
        if (UserHolder.getUser() == null) {
            // 没有，需要拦截，设置状态码
            try (PrintWriter printWriter = response.getWriter()) {
                response.setCharacterEncoding("UTF-8");
                response.setContentType("application/json; charset=utf-8");
                ObjectMapper objectMapper = new ObjectMapper();
                Result<Object> result = Result.fail("not login");
                result.setStatus(401);
                printWriter.write(objectMapper.writeValueAsString(result));
                // response.setStatus(401);
                // 拦截
                return false;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        // 有用户，放行
        return true;
    }
}
